import axios from 'axios'
import {Message} from 'element-ui';
import router from '../router'
import {customMessage} from "@/utils/customMessage";
import qs from 'qs';

axios.interceptors.request.use(
    config => {

        // 这里的config包含每次请求的内容
        let tokenObj = JSON.parse(window.localStorage.getItem('token'));
        if (tokenObj) {
            let token = tokenObj.token;
            // 添加headers
            config.headers['token'] = `${token}`;
            config.headers['Authorization'] = "Bearer " + `${token}`;
            config.headers['content-type'] = 'application/json;charset=UTF-8';
        }

        //只针对get方式进行序列化
        if (config.method === 'get') {
            config.paramsSerializer = function(params) {
                return qs.stringify(params, { arrayFormat: 'repeat'})
            }
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

axios.interceptors.response.use(success => {
    if (success.status && success.status === 200 && success.data.status && (success.data.status === 403 || success.data.status === 401)) {
        localStorage.removeItem('token');
        window.location.href = "/#/login";
    }
    if (success.status && success.status === 200 && success.data.status && success.data.status !== 200) {
        Message.error({message: success.data.message});
        return;
    }
    if (success.status && success.status === 200 && success.data.message && success.data.message !== '请求成功') {
        Message.success({message: success.data.message})
    }

    return success.data;
}, error => {
    if (error.response) {
        if (error.response.status === 504 || error.response.status === 404) {
            Message.error({message: '服务器被吃了( ╯□╰ )'})
        } else if (error.response.status === 403) {
            Message.error({message: '权限不足，请联系管理员'})
        } else if (error.response.status === 401) {
            customMessage.error({message: error.response.data.message ? error.response.data.message : '尚未登录，请登录'})
            router.replace('/');
        } else {
            if (error.response.data.message) {
                Message.error({message: error.response.data.message})
            } else {
                Message.error({message: '未知错误!'})
            }
        }
    } else {
        alert(JSON.stringify(error));
        alert("无响应");
    }

})

// 对应后端统一的接口前缀
let contextPath = '/api';

export const postKeyValueRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${contextPath}${url}`,
        data: params,
        transformRequest: [function (data) {
            let ret = '';
            for (let i in data) {
                ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
            }
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
}
export const postRequest = (url, params) => {
    let tokenObj = JSON.parse(window.localStorage.getItem('token'));
    // POST 只有登录接口放行请求，其他接口需要在token有效期内发起请求，否则跳转登录页
    if (url.indexOf("/login") > 0 || (tokenObj && tokenObj.time > new Date().getTime())) {
        return axios({
            method: 'post',
            url: `${contextPath}${url}`,
            data: params
        });
    } else {
        window.location.href = "/#/login";
        Message.warning("登录状态已过期，请重新登录！");
        return false;
    }
}

export const exportFileRequest = (url, params) => {
    let tokenObj = JSON.parse(window.localStorage.getItem('token'));
    // POST 只有登录接口放行请求，其他接口需要在token有效期内发起请求，否则跳转登录页
    if (url.indexOf("/login") > 0 || (tokenObj && tokenObj.time > new Date().getTime())) {
        return axios({
            method: 'post',
            url: `${contextPath}${url}`,
            data: params,
            responseType: 'blob',
        });
    } else {
        window.location.href = "/#/login";
        Message.warning("登录状态已过期，请重新登录！");
        return false;
    }
}

export const putRequest = (url, params) => {
    let tokenObj = JSON.parse(window.localStorage.getItem('token'));
    if (tokenObj && tokenObj.time > new Date().getTime()) {
        return axios({
            method: 'put',
            url: `${contextPath}${url}`,
            data: params
        })
    } else {
        window.location.href = "/#/login";
        Message.warning("登录状态已过期，请重新登录！");
        return false;
    }
}

export const getRequest = (url, params) => {
    let tokenObj = JSON.parse(window.localStorage.getItem('token'));
    if (tokenObj && tokenObj.time > new Date().getTime()) {
        return axios({
            method: 'get',
            url: `${contextPath}${url}`,
            params: params
        })
    } else {
        window.location.href = "/#/login";
        Message.warning("登录状态已过期，请重新登录！");
        return false;
    }
}

export const deleteRequest = (url, params) => {
    let tokenObj = JSON.parse(window.localStorage.getItem('token'));
    if (tokenObj && tokenObj.time > new Date().getTime()) {
        return axios({
            method: 'delete',
            url: `${contextPath}${url}`,
            params: params
        })
    } else {
        window.location.href = "/#/login";
        Message.warning("登录状态已过期，请重新登录！");
        return false;
    }
}
